package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.LoginCode;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CacheManager cacheManager;

    /**
     * 保存套餐以及菜品信息
     *
     * @param setmealDto
     */
    @Override
    @CacheEvict(value = LoginCode.SETMEALLIST_REDIS_KEY,allEntries = true)
    @Transactional
    public void saveSetmealWithDish(SetmealDto setmealDto) {
        //直接添加套餐
        this.save(setmealDto);
        //获取保存的套餐id,给每个菜品传入id
        Long id = setmealDto.getId();

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(id);
        }

        //保存到关系表里
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<SetmealDto> pageWithCategory(Integer page, Integer pageSize, String name) {
        //先对套餐进行分页
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> lqw1 = new LambdaQueryWrapper<>();
        lqw1.like(StringUtils.isNotBlank(name), Setmeal::getName, name)
                .orderByDesc(Setmeal::getUpdateTime);
        this.page(setmealPage, lqw1);
        //复制到dto里
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(setmealPage, setmealDtoPage);

        List<SetmealDto> setmealDtos = new ArrayList<>();
        setmealDtoPage.setRecords(setmealDtos);

        //判断模糊搜索是否有值,空值则直接返回
        //获取分页套餐数据
        List<Setmeal> setmeals = setmealPage.getRecords();
        if (setmeals.size() == 0) {
            return setmealDtoPage;
        }
        //根据setmeals获取分类id
        Set<Long> ids = new HashSet<>();
        for (Setmeal setmeal : setmeals) {
            ids.add(setmeal.getCategoryId());
        }
        //到分类表里根据id查找名称
        List<Category> categories = categoryService.listByIds(ids);

        //遍历setmeals 和 套餐名称集合 进行一一对比
        for (Setmeal setmeal : setmeals) {

            for (Category category : categories) {
                if (setmeal.getCategoryId().equals(category.getId())) {
                    //比对成功将setmeal和对应套餐名称存入setmealDtos集合
                    SetmealDto setmealDto = new SetmealDto();
                    BeanUtils.copyProperties(setmeal, setmealDto);
                    setmealDto.setCategoryName(category.getName());

                    setmealDtos.add(setmealDto);
                    break;
                }
            }
        }

        return setmealDtoPage;
    }

    @Override
    @Transactional
    @CacheEvict(value = LoginCode.SETMEALLIST_REDIS_KEY,allEntries = true)
    public void deleteWithDish(List<Long> ids) {
        //删套餐之前先查询判断该套餐是否启用
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, 1);
        int count = this.count(lqw);
        if (count > 0) {
            throw new CustomException("该套餐正在售卖中,不能删除");
        }

        //进行删除操作
        //先删除套餐表
        this.removeByIds(ids);
        //删除关系表
        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getSetmealId, ids);

        setmealDishService.remove(lqw1);
    }

    /**
     * 获取该套餐下全部菜品信息
     *
     * @param id
     * @return
     */
    @Override
    public List<DishDto> getDish(Long id) {
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId, id);

        //获取改套餐下全部菜品id
        List<SetmealDish> list = setmealDishService.list(lqw);
        List<Long> dishIds = new ArrayList<>();
        for (SetmealDish setmealDish : list) {
            dishIds.add(setmealDish.getDishId());
        }
        //根据获取菜品集合
        List<Dish> dishList = dishService.listByIds(dishIds);

        //创建既有菜品又有菜品数量的集合
        List<DishDto> dishDtoList = new ArrayList<>();

        for (SetmealDish setmealDish : list) {

            for (Dish dish : dishList) {
                if (setmealDish.getDishId().equals(dish.getId())) {
                    DishDto dishDto = new DishDto();
                    //增加菜品相应的份数
                    dishDto.setCopies(setmealDish.getCopies());
                    BeanUtils.copyProperties(dish, dishDto);
                    dishDtoList.add(dishDto);
                    break;
                }

            }

        }

        return dishDtoList;
    }

    /**
     * 批量修改套餐状态
     * @param status
     * @param ids
     */
    @Override
    @CacheEvict(value = LoginCode.SETMEALLIST_REDIS_KEY,allEntries = true)
    public void updateStatus(Integer status, List<Long> ids) {
        LambdaUpdateWrapper<Setmeal> lqw = new LambdaUpdateWrapper<>();

        lqw.in(Setmeal::getId,ids).set(Setmeal::getStatus,status);

        this.update(lqw);

    }

    /**
     * 根据id进行查询套餐,及套餐下的菜品信息
     * @param id
     * @return
     */
    @Override
    public SetmealDto getWithDish(Long id) {
        //先查询套餐
        Setmeal setmeal = this.getById(id);

        //查询套餐下的菜品.
        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(SetmealDish::getSetmealId,id);
        //对应套餐信息及其份数
        List<SetmealDish> list = setmealDishService.list(lqw1);

        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(list);
        return setmealDto;
    }

    /**
     * 修改套餐信息
     * @param setmealDto
     */
    @Override
    @CacheEvict(value = LoginCode.SETMEALLIST_REDIS_KEY,allEntries = true)
    @Transactional
    public void updateWithDish(SetmealDto setmealDto) {
        //直接修改套餐
        this.updateById(setmealDto);

        //先全部删除套餐菜品关系表里的数据,再添加

        LambdaQueryWrapper<SetmealDish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(lqw1);

        //再添加
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //遍历setmealDishes添加setmealid
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //添加至关系表数据
        setmealDishService.saveBatch(setmealDishes);

    }
}
